﻿//-----------------------------------------------------------------------
// <copyright file="ClassRepository.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings

using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using GateShift.Common.Repository;
using GateShift.Common.Repository.Interfaces.DataInterfaces;
using GateShift.Common.Repository.Interfaces.Repositories;
using GateShift.Services.GameData.Entities;

#endregion

namespace GateShift.Services.GameData.Repositories
{
    /// <summary>
    /// General repository for managing Classes
    /// </summary>
    internal class ClassRepository : IClassRepository
    {
        #region CTor/DTor

        /// <summary>
        /// Initializes a new instance of the ClassRepository class
        /// </summary>
        /// <param name="connection">Reference to the common EntityConnection for the repository</param>
        internal ClassRepository(EntityConnection connection)
        {
            Connection = connection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a reference to the common EntityConnection for the repository
        /// </summary>
        protected EntityConnection Connection { get; private set; }

        #endregion

        #region IRepository<IClassData> Members

        /// <summary>
        /// Retrieves all instances of IClassData from the repository
        /// </summary>
        /// <returns>List of the requested IClassData</returns>
        public IList<IClassData> Retrieve()
        {
            List<IClassData> returnValues = new List<IClassData>();

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                foreach (Class gameClass in from item in dataSource.Classes select item)
                {
                    returnValues.Add(gameClass);
                    dataSource.Detach(gameClass);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves the requested IClassData by an Identity
        /// </summary>
        /// <param name="ID">Identity to retrieve the data by</param>
        /// <returns>IClassData instance or null if one was not found</returns>
        /// <exception cref="InvalidCastException">Thrown if the identity is of the wrong type for this datasource</exception>
        public IClassData Retrieve(Identity ID)
        {
            if (!ID.CanFitInInt64())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Int64/int/Int16 Type. Currently is {0}.", ID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            long searchID = ID;

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                Class foundClass = (from
                                           gameClass
                                           in
                                        dataSource.Classes
                                    where
                                        gameClass.ClassID == searchID
                                    select
                                        gameClass).FirstOrDefault();

                if (foundClass != null)
                {
                    dataSource.Detach(foundClass);
                }

                return foundClass;
            }
        }

        /// <summary>
        /// Deletes the requested IClassData
        /// </summary>
        /// <param name="Data">IClassData to delete from the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        /// <exception cref="InvalidOperationException">Thrown if the IClassData is new or already deleted</exception>
        public void Delete(IClassData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Class))
            {
                throw new InvalidCastException("Data is not of type Class. Cannot delete this object through this repository");
            }

            if (Data.IsNew)
            {
                throw new InvalidOperationException("Data cannot be new before deleting. There is nothing to delete.");
            }

            if (Data.IsDeleted)
            {
                throw new InvalidOperationException("Data already deleted.");
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                dataSource.Attach((Class)Data);
                dataSource.DeleteObject(Data);
                dataSource.SaveChanges();
            }
        }

        /// <summary>
        /// Saves the requested IClassData
        /// </summary>
        /// <param name="Data">IClassData to save to the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        public void Save(IClassData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Class))
            {
                throw new InvalidCastException("Data is not of type Class. Cannot save this object through this repository");
            }

            if (!Data.IsDirty)
            {
                return;
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                if (Data.IsNew)
                {
                    dataSource.AddToClasses((Class)Data);
                    dataSource.SaveChanges();
                    dataSource.Detach(Data);
                }
                else
                {
                    dataSource.ApplyPropertyChanges("Classes", Data);
                    dataSource.SaveChanges();
                }
            }
        }

        /// <summary>
        /// Creates a new instance of IClassData
        /// </summary>
        /// <returns>New Instance of IClassData</returns>
        public IClassData Create()
        {
            return new Class();
        }

        #endregion
    }
}